<template>
    <!-- <view class="login" style="background: url(http://60.191.72.66:10088/business/image/jdzy/applet/static/login/login-bg1.png) 100% 20%/120% 120%;"> -->
    <!-- <view class="login" style="background: url(/static/login/login-bg1.png) 100% 20%/120% 120%;"> -->
    <view class="login">
        <!-- 当设置 "navigationStyle":"custom" 取消原生导航栏后，由于窗体为沉浸式，占据了状态栏位置。此时可以使用一个高度为 var(--status-bar-height) 的 view 放在页面顶部，避免页面内容出现在状态栏。 -->
        <view class="bar-height"></view>
        <view class="logo"></view>
        <view class="login-text">登录账号</view>
        <!-- 登录账号 -->
        <view 
            v-show='showType == "手机号登录"'
            class="myforms"
        >
            <uni-forms
                 :model="formData2" 
                 ref="form2" 
                 :rules="rules2" 
                 validateTrigger="submit" 
                 label-width="60px"
                 err-show-type='none'
             >
                 <uni-forms-item
                     name="phone"
                     label="手机号"
                 >
                      <view class="phone-vc">
                         <uni-easyinput
                             type="number" 
                             v-model="formData2.phone" 
                             maxlength="11"
                             placeholder="请输入手机号" 
                         />
                         <button
                             type="default"
                             :disabled="vcText != '验证码'"
                             @click="getVc(formData2.phone)"
                         >
                             {{ vcText }}
                         </button>
                      </view>
                  </uni-forms-item>
                  <uni-forms-item 
                     name="vc"
                     label="验证码"
                 >
                      <uni-easyinput 
                         type="number" 
                         v-model="formData2.vc" 
                         placeholder="请输入验证码" 
                     />
                  </uni-forms-item>
             </uni-forms>
             <view class="checkbox-class">
                 <uni-data-checkbox 
                     v-model="checkbox1Checked" 
                     :localdata="checkbox1Range" 
                     @change="checkbox1Change"
                 ></uni-data-checkbox>
                <span>
                     我已阅读并同意
                     <span 
                        style="color: rgb(67, 111, 255);"
                        @click="alertDialog.open()"
                    >
                        非紧急转运用户协议
                    </span>
                </span>
                 
             </view>
            <button  @click="submit2">登录</button>
            <view class="tips">
                <view @click='showType = "用户授权登录"'>用户授权登录</view>
            </view>
        </view>
        <view
            v-show='showType == "用户授权登录"'
            class="myforms"
        >
            <view class="checkbox-class">
                <uni-data-checkbox 
                    v-model="checkbox1Checked" 
                    :localdata="checkbox1Range" 
                    @change="checkbox1Change"
                ></uni-data-checkbox>
                <span>
                     我已阅读并同意
                     <span 
                        style="color: rgb(67, 111, 255);"
                        @click="alertDialog.open()"
                    >
                        非紧急转运用户协议
                    </span>
                </span>
            </view>
            <!-- <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">用户授权登录</button> -->
            <button :disabled="checkbox1Checked != 1" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">用户授权登录</button>
            <!-- <view class="tips">
                <view @click='showType = "手机号登录"'>手机号登录</view>
            </view> -->
        </view>
        
        <uni-popup 
            ref="alertDialog" 
            type="dialog"
            :is-mask-click="false"
        >
            <uni-popup-dialog 
                type="base" 
                cancelText="不同意" 
                confirmText="同意" 
                title="非紧急转运用户协议" 
                @confirm="dialogConfirm"
                @close="dialogClose"
            >
                <template #default>
                    <view class="dialog-content">
                        <view class="dialog-text-1">特别说明:</view>
                        <view class="dialog-text-2">非急救转运车不配备专业医护人员和医疗急救设备，仅为出院或转院非急救患者提供搬抬、转运的非急救转运服务。在转运过程中，如因患者身体或病情原因，发生与医疗相关的风险，我方工作人员将根据家属要求紧急转往就近医院。因我方无医护服务资质，从而不能承担相应医疗职责。</view>
                        <view class="dialog-text-1">温馨提示:</view>
                        <view class="dialog-text-2">感谢您使用非急救转运服务，通过4008897120呼叫、实时下单及预订。本车不配备专业医护人员和医疗急救设备，仅为出院或转院非急救患者提供搬抬、转运的非急救转运服务。如您对我方服务有任何意见或建议，请拨打客服电话4008897120。</view>
                        <view class="dialog-text-2">患者及/家属已仔细阅读本告知书全部内容，已完全知晓与理解在转运过程中可能存在医疗风险，并同意我方实施非急救转运的服务。如在我方提供服务的过程中发生任何非我方过错导致的意外情况，我方不承担任何相关责任。本次非急救转运的行驶路线与患者或家属进行沟通并双方确认，无异议。</view>
                    </view>
                </template>
            </uni-popup-dialog>
        </uni-popup>
    </view>
</template>

<script lang="ts" setup>
    import { onLoad, onShow, onHide, onReady, onUnload } from '@dcloudio/uni-app'
    import { markRaw, onBeforeUnmount, reactive, ref } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { smsSendVcApi, userRegisterApi, wxAppletLoginApi, getWxPhoneApi } from '@/apis/index'
    import { isPhone } from '@/utils/utils'
    console.log('login page')
    const getPhoneNumber = async(e) => {
        // if (checkbox1Checked.value != 1) {
        //     uni.showToast({
        //     	title: '请阅读并同意非紧急急救转运用户协议',
        //         icon: 'error',
        //     	duration: 1500,
        //         mask: true,
        //     });
        //     return false;
        // }
        try {
            let res2 = await getWxPhoneApi({
                code: e.detail.code,
            })
            uni.setStorageSync('storagePhone', res2.data)
            uni.login({
                provider: 'weixin', //使用微信登录
                onlyAuthorize: true,
                success: function (loginRes) {        
                    console.log(loginRes);
                    // console.log(loginRes.authResult);
                    wxAppletLoginApi({
                        code: loginRes.code,
                        phone: uni.getStorageSync('storagePhone'),
                    }).then(res3 => {
                        if (res3.code == 200) {
                            uni.setStorageSync('token', res3.data)
                            if (redirectUrl) {
                                uni.reLaunch({
                                	url: redirectUrl
                                });
                            } else {
                                uni.reLaunch({
                                	url: '/pages/index/index'
                                });
                            }
                        }
                    })
                    // uni.switchTab({
                    //     url: "/pages/index/index"
                    // })
                },
                fail(err) {
                    uni.showToast({
                        icon: "error",
                        mask: true,
                        title: '请稍后再试'
                    });
                	console.error(err);
                },
                complete() {
                    // uni.hideLoading();
                }
            });
        } catch(err) {
            uni.showToast({
                icon: "error",
                mask: true,
                title: '请稍后再试'
            });
        }
    }
    const alertDialog: Ref<any> = ref(null)
    const checkbox1Range = [{"value": 1,"text": ""}]
    const checkbox1Checked: Ref<number> = ref(0)
    const checkbox1Change = (val: any) => {
        console.log(val.detail.value)
        if (val.detail.value == 1) {
            alertDialog.value.open()
        }
    }
    const dialogConfirm = (val) => {
        console.log(val)
        checkbox1Checked.value = 1
    }
    const dialogClose = (val) => {
        checkbox1Checked.value = 0
    }
    const showType: Ref<string> = ref('用户授权登录')
    const formData2: any = reactive({
        phone: '',
        vc: '',
    })
    const rules2: any = reactive({
        phone: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入手机号',
                },{
                    validateFunction: function(rule, value, data, callback){
                        if (!isPhone(value)) {
                            callback('请输入正确的手机号')
                        }
                        return true
                    }
                }
            ],
        },
        vc: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入验证码',
                },
            ],
        }
    })
    const vcText: Ref<string> = ref('验证码')
    const vcNum: Ref<number> = ref(10)
    const vcInterval: Ref<any> = ref('')
    const getVc = ((val: number) => {
        if (!isPhone(val)) {
            uni.showToast({
            	title: '请输入正确的手机号',
                icon: 'error',
            	duration: 1500,
                mask: true,
            });
        } else {
            vcNum.value = 10
            vcText.value = vcNum.value + 's'
            vcInterval.value = setInterval(() => {
                vcNum.value--
                vcText.value = vcNum.value + 's'
                if (vcNum.value <= 0) {
                    clearInterval(vcInterval.value)
                    vcText.value = '验证码'
                }
            }, 1000)
            smsSendVcApi({
                mobile: val,
                type: 2,
            }).then((res: any) => {
                if (res.code == 200) {
                    uni.showToast({
                    	title: res.msg,
                        icon: 'none',
                    	duration: 1500,
                        mask: true,
                    });
                } else {
                    uni.showToast({
                    	title: res.msg,
                        icon: 'error',
                    	duration: 1500,
                        mask: true,
                    });
                }
            })
        }
    })
    const form2: Ref<any> = ref(null)
    // 如果需要使用 validateFunction 自定义校验规则,则不能采用 uni-forms 的 rules 属性来配置校验规则，这时候需要通过ref，在onReady生命周期调用组件的setRules方法绑定验证规则
    onReady(() => {
        form2.value.setRules(rules2)
    })
    let redirectUrl = ''
    onLoad((opt: any) => {
        console.log(opt)
        if (opt.url) {
            redirectUrl = opt.url
        }
    })
    const submit2 = () => {
        if (checkbox1Checked.value != 1) {
            uni.showToast({
            	title: '请阅读并同意非紧急急救转运用户协议',
                icon: 'error',
            	duration: 1500,
                mask: true,
            });
            return false;
        }
        console.log(form2.value)
        form2.value.validate().then((res1: any) => {
            console.log('表单数据信息：', res1);
            // 调接口
            let formd2: any = JSON.parse(JSON.stringify(formData2))
            userRegisterApi(formd2).then((res2: any) => {
                console.log(res2)
                if (res2.code == 200) {
                    uni.showModal({
                        showCancel: false,
                    	title: '提示',
                    	content: res2.msg,
                    	success: function (res) {
                            uni.setStorageSync('token', res2.data)
                            if (redirectUrl) {
                                uni.reLaunch({
                                	url: redirectUrl
                                });
                            } else {
                                uni.reLaunch({
                                	url: '/pages/index/index'
                                });
                            }
                    		// if (res.confirm) {
                    		// 	console.log('用户点击确定');
                    		// } else if (res.cancel) {
                    		// 	console.log('用户点击取消');
                    		// }
                    	}
                    });
                } else {
                    uni.showToast({
                    	title: res2.msg,
                        icon: 'error',
                    	duration: 1500,
                        mask: true,
                    });
                }
            })
            
        }).catch((err: any) =>{
            console.log('表单错误信息：', err);
            console.log(err);
            uni.showToast({
            	title: err[0].errorMessage,
                icon: 'error',
            	duration: 1500,
                mask: true,
            });
        })
    }
    onUnload(() => {
        if (vcInterval.value) {
            clearInterval(vcInterval.value)
        }
    })
</script>

<style lang="scss" scoped>
    .login::before {
        content: '';
        width: 100vw;
        // height: 100vh;
        height: calc(100vh - var(--window-top) - var(--window-bottom)); //var(--window-top) 页面的内容区域距离顶部距离 var(--window-bottom) 页面的内容区域距离底部距离 app不存在，h5有这两个高度
        // background: url(@/static/login/login-bg4.png) 50% 70%/120% 110%;
        // background-size: 100% 100%;
        box-sizing: border-box;
        padding: 0 60rpx;
        // display: flex;
        // flex-direction: column;
        // align-items: center;
        position: absolute;
        z-index: -1;
        overflow: hidden;
        
        background: url(http://60.191.72.66:10088/business/image/jdzy/applet/static/login/login-bg1.png);
        background-size: 100% 100%;
        // filter: blur(15rpx);
    }
    .login {
        width: 100vw;
        height: calc(100vh - var(--window-top) - var(--window-bottom)); //var(--window-top) 页面的内容区域距离顶部距离 var(--window-bottom) 页面的内容区域距离底部距离 app不存在，h5有这两个高度
        position: absolute;
    }
    .bar-height {
        width: 100vw;
        height: var(--status-bar-height);
    }
    .logo {
        width: 140rpx;
        height: 140rpx;
        background: url(http://60.191.72.66:10088/business/image/jdzy/applet/static/logo.png);
        background-size: 100% 100%;
        margin: 60rpx auto 60rpx;
    }
    .login-text {
        padding: 20rpx 40rpx;
        color: #fff;
        font-weight: bold;
        text-shadow: 0 0rpx 10rpx #aaaaff;
    }
    .myforms {
        background-color: rgba(255, 255, 255, 0.2);
        padding: 60rpx 40rpx;
        box-sizing: border-box;
        min-height: 400rpx;
        overflow-x: hidden;
        overflow-y: scroll;
        
    }
    :deep(.myforms .uni-forms-item__label) {
        color: #fff;
    }
    .phone-vc {
        display: flex;
        button {
            width: 150rpx;
            height: 74rpx;
            font-size: 30rpx;
        }
    }
    .tips {
        box-sizing: border-box;
        padding: 60rpx 0 0 0;
        display: flex;
        justify-content: space-between;
        color: #fff;
    }
    .checkbox-class {
        display: flex;
        align-items: center;
        padding: 30rpx 0;
        box-sizing: border-box;
    }
    .dialog-content {
        height: 800rpx;
        overflow: scroll;
        .dialog-text-1 {
            font-weight: bold;
        }
        .dialog-text-2 {
            color: #313131;
            text-indent: 70rpx;
            line-height: 50rpx;
        }
    }
    :deep(.uni-data-checklist .checklist-group .checklist-box) {
        margin-right: 10rpx;
    }
</style>
